import { PageList } from "@mallfoundry/shared/data"
import { Staff, StaffService } from "@mallfoundry/store/staff"
import { useEffect, useState } from "react"

export function useStaff(storeId: string, staffId: string) {
  const [staff, setStaff] = useState(new Staff())
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    setLoading(true)
    StaffService.getStaff({ storeId, id: staffId }).then(setStaff)
      .finally(() => setLoading(false))
  }, [storeId, staffId])

  return { loading, staff }
}

interface UseStaffsOptions {
  storeId?: string
  roleIds?: string | string[]
}

export function useStaffs(options: UseStaffsOptions) {
  const { storeId, roleIds } = options
  const [pageStaffs, setPageStaffs] = useState<PageList<Staff>>(PageList.empty())
  const [loading, setLoading] = useState(false)

  useEffect(refresh, [storeId, roleIds])

  function refresh() {
    setLoading(true)
    StaffService.getStaffs(
      StaffService.createStaffQuery()
        .toBuilder()
        .storeId(storeId)
        .roleIds(roleIds)
        .build())
      .then(setPageStaffs)
      .finally(() => setLoading(false))
  }

  return {
    loading,
    refresh,
    ...pageStaffs,
  }
}
